const path = require('path');

const commonWebpackConfig = {
  entry: './src/main.js',
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      'assets': path.resolve(__dirname, 'src/assets'),
      'components': path.resolve(__dirname, 'src/components')
    }
  },
  plugins: []
};

const baseConfig = {
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
  outputDir: 'dist',
  configureWebpack: commonWebpackConfig,
  chainWebpack: config => {
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({ bypassOnDebug: true });

    config.plugins.delete('preload');
    config.plugins.delete('prefetch');
  },
  css: {
    loaderOptions: {
      sass: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  }
};

const devConfig = {
  ...baseConfig,
  devServer: {
    port: 8080, // 开发环境端口
    open: true,
    proxy: {
      '/api': {
        target: process.env.VUE_APP_API_URL,
        changeOrigin: true,
        pathRewrite: { '^/api': '' }
      }
    }
  }
};

const stagingConfig = {
  ...baseConfig,
  publicPath: '/staging/',
  configureWebpack: {
    ...commonWebpackConfig,
    output: {
      filename: 'js/[name].[hash].js',
      chunkFilename: 'js/[name].[hash].js'
    },
    optimization: {
      minimize: true
    }
  },
  css: {
    loaderOptions: {
      sass: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  },
  productionSourceMap: false,
  devServer: {
    port: 8081, // 预发布环境端口
    open: true
  }
};

const prodConfig = {
  ...baseConfig,
  configureWebpack: {
    ...commonWebpackConfig,
    optimization: {
      minimize: true
    }
  },
  productionSourceMap: false,
  devServer: {
    port: 8082, // 生产环境调试端口
    open: true
  }
};

module.exports = (config, env) => {
  if (env === 'development') return devConfig;
  if (env === 'staging') return stagingConfig;
  if (env === 'production') return prodConfig;

  return baseConfig;
};